<template>
	<view class="container">
		<!-- 饼状图 -->
		<view class="chart-container">
			<qiun-data-charts type="pie" :opts="chartOpts" :chartData="chartData" />
		</view>
		<!-- 列表区域 -->
		<view class="wrap">
			<!-- <view class="search">
				<u-search v-model="keywords" @custom="search" @search="search"></u-search>
			</view> -->
			<view class="list-container">
				<u-cell-group class="list" :border="false">
					<u-swipe-action class="list-item" :options="options" v-for="(item, index) in list" :key="item.id" :index="index" @click="optionsClick">
						<u-cell-item :arrow="false">
							<text slot="title">{{item.mainName}}</text>
							<text slot="label">
								<view>
									<text>金额：{{item.quantity}}{{item.unit == '01' ? '元' : '张'}}</text>
									<text>{{item.ownOfficeName == '' ? '':('本店店铺：'+ item.ownOfficeName)}}</text>
								</view>
								<view>
									<text>{{type == 9 ? '发生日期':'销售日期'}}：{{item.startSaleDate}}</text>
									<text>{{item.officeName == '' ? '':('分店名称：'+item.officeName)}}</text>
								</view>
							</text>
						</u-cell-item>
					</u-swipe-action>
				</u-cell-group>
			</view>
			
			<!-- 合计区域 -->
			<view class="total-bar" @click="showTotalDetail">
				<view class="total-item">
					<text>销售额：</text>
					<text class="value">¥{{totalAmount}}</text>
				</view>
				<view class="total-item">
					<text>销售笔数：</text>
					<text class="value">{{totalCount}}</text>
				</view>
			</view>
		</view>
		<!-- 合计详情弹窗 -->
		<u-popup v-model="showDetail" mode="bottom" border-radius="20">
			<view class="total-detail">
				<view class="detail-header">
					<text class="title">合计数据</text>
					<view class="close-btn" @click="showDetail = false">×</view>
				</view>
				<view class="detail-content">
					<view class="detail-item">
						<text class="label">销售额：</text>
						<text class="value">¥{{totalAmount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">销售笔数：</text>
						<text class="value">{{totalCount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">开单金额：</text>
						<text class="value">¥{{totalAmount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">开单笔数：</text>
						<text class="value">{{totalCount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">销售毛利：</text>
						<text class="value">¥{{totalProfit}}</text>
					</view>
					<view class="detail-item">
						<text class="label">税额：</text>
						<text class="value">¥{{tax}}</text>
					</view>
					<view class="detail-item">
						<text class="label">退货额：</text>
						<text class="value">¥{{refundAmount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">折扣额：</text>
						<text class="value">¥{{discountAmount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">销售量：</text>
						<text class="value">{{salesVolume}}</text>
					</view>
					<view class="detail-item">
						<text class="label">销售开单量：</text>
						<text class="value">{{salesVolume}}</text>
					</view>
					<view class="detail-item">
						<text class="label">退货量：</text>
						<text class="value">{{refundVolume}}</text>
					</view>
					<view class="detail-item">
						<text class="label">应收欠款：</text>
						<text class="value">¥{{receivables}}</text>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
export default {
	data() {
		return {
			type:1,
			keywords: '',
			query: {
				pageNo: 1,
				pageSize: 2000,
				subType:'',
				mainType:'',
			},
			list: [],
			count: 0,
			loadStatus: 'loadmore',
			options: [
				// {text: '删除', style: { background: '#dd524d'}},
				// {text: '上传', style: { background: '#414ee0'}},
			],
			mainTypeList:[],
			// 图表配置
			chartOpts: {
				title: {
					name: '',//销售分布
					fontSize: 15,
					color: '#666666'
				},
				subtitle: {
					name: '',
					fontSize: 12,
					color: '#999999'
				},
				extra: {
					pie: {
						lableWidth: 15,
						ringWidth: 40, // 环形宽度
						centerColor: '#ffffff' // 中心颜色
					}
				},
				legend: {
					show: true,
					position: 'right',
					lineHeight: 25
				},
				animation: true
			},
			// 图表数据
			chartData: {
				series: []
			},
			showDetail: false, // 控制合计详情弹窗
			totalAmount: '361600.00', // 销售总额
			totalCount: '15', // 销售笔数
			totalProfit: '28928.00', // 销售毛利
			tax: '0.00', // 税额
			refundAmount: '0.00', // 退货额
			discountAmount: '0.00', // 折扣额
			salesVolume: '575', // 销售量
			refundVolume: '0', // 退货量
			receivables: '53000.00', // 应收欠款
		};
	},
	onLoad(params) {
		this.type = params.type
		// 设置页面标题
		let title = ''
		if(this.type == 1){
			title = '销售报表'
			// this.query.subType = 'HM'
		}else if(this.type == 2){
			title = '佣金报表'
			// this.query.subType = 'BFD'
		}else if(this.type == 3){
			title = '支出报表'
			// this.query.subType = 'GFD'
		}
		uni.setNavigationBarTitle({
			title: title
		});
		// 主类型
		this.$u.api.mainType.treeData({dictType:'sale_main_type'}).then(res => {
			this.mainTypeList = res;
			this.loadList();
		});
		// 初始化图表数据
		this.initChartData();
	},
	onShow() {
		if (uni.getStorageSync('refreshList') === true){
			uni.removeStorageSync('refreshList');
			this.search('');
		}
	},
	methods: {
		findNameByValue(array, value) {
		    const foundObject = array.find(item => item.dictValue == value);
		    return foundObject ? foundObject.dictLabel : null;
		},
		loadMore() {
			this.loadStatus = "loading";
			setTimeout(() => {
				this.query.pageNo += 1;
				this.loadList();
			}, 100);
		},
		loadList() {
			let that = this
			this.$u.api.salesManagement.list(this.query).then(res => {
				if (!res.list || res.list.length == 0){
					this.loadStatus = "nomore";
					return;
				}
				
				// 先处理mainName
				res.list.forEach(function(e) {
					e.mainName = that.findNameByValue(that.mainTypeList, e.mainType);
				});
				
				// 按mainType合并数据
				const mergedMap = {};
				res.list.forEach(item => {
					// 如果是type==1，只统计特定的mainType
					if (this.type == 1) {
						const validTypes = ['01', '02', '03', '04', '05', '06', '07', '08', '12'];
						if (!validTypes.includes(item.mainType)) {
							return; // 跳过不符合条件的记录
						}
					}
					// 如果是type==2，只统计特定的mainType
					if (this.type == 2) {
						const validTypes = ['09', '10', '11', '13'];
						if (!validTypes.includes(item.mainType)) {
							return; // 跳过不符合条件的记录
						}
					}
					// 如果是type==3，只统计特定的mainType
					if (this.type == 3) {
						const validTypes = ['14', '15', '16', '17','18', '19', '20', '21','22', '23', '24', '25','26', '27'];
						if (!validTypes.includes(item.mainType)) {
							return; // 跳过不符合条件的记录
						}
					}
					
					if (!mergedMap[item.mainType]) {
						mergedMap[item.mainType] = {
							...item,
							quantity: parseFloat(item.quantity) || 0
						};
					} else {
						mergedMap[item.mainType].quantity += parseFloat(item.quantity) || 0;
					}
				});
				
				// 转换为数组
				this.list = Object.values(mergedMap);
				
				this.count = this.list.length;
				this.query.pageNo = res.pageNo;
				this.query.pageSize = res.pageSize;
				this.loadStatus = "loadmore";
				
				// 更新图表数据
				this.initChartData();
				
				// 计算合计数据
				this.calculateTotal();
			});
		},
		optionsClick(rowIndex, btnIndex) {
			let self = this, row = self.list[rowIndex];
			if(btnIndex == 1) {
				this.navTo('formUpload?id='+row.id);
			} else if(btnIndex == 0) {
				uni.showModal({
					title: '提示',
					content: '确认要删除该数据吗？',
					showCancel: true,
					success: function (res2) {
						if (res2.confirm) {
							self.$u.api.salesManagement.delete({id: row.id}).then(res => {
								self.$u.toast(res.message);
								if (res.result == 'true'){
									self.list.splice(rowIndex, 1);
								}
							});
						}
					}
				});
			}
		},
		search(value) {
			this.list = [];
			this.query.pageNo = 0;
			// this.query.testInput = value;
			this.loadList();
		},
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		initChartData() {
			// 直接使用合并后的list数据
			if (this.list && this.list.length > 0) {
				// 转换为图表数据
				this.chartData.series = this.list.map(item => ({
					name: item.mainName,
					data: parseFloat(item.quantity) || 0
				}));
			}
		},
		showTotalDetail() {
			this.showDetail = true;
		},
		// 计算合计数据
		calculateTotal() {
			if (this.list && this.list.length > 0) {
				// 计算销售总额
				this.totalAmount = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.quantity) || 0);
				}, 0).toFixed(2);
				
				// 计算销售笔数
				this.totalCount = this.list.length.toString();
				
				// 计算销售毛利（这里假设毛利是销售额的8%）
				this.totalProfit = (this.totalAmount * 0.08).toFixed(2);
				
				// 计算销售量（这里假设每笔销售量为1）
				this.salesVolume = this.list.length.toString();
			}
		}
	}
};
</script>

<style lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	// padding: 20rpx;
	box-sizing: border-box;
}

.chart-container {
	width: 100%;
	max-height: 1200rpx;
	margin-bottom: 50rpx;
}

page {
	background-color: #f8f8f8;
}
.btn-plus {
	position: absolute;
	bottom: 50rpx;
	right: 50rpx;
	z-index: 1;
	opacity: 0.6;
}
.btn-plus:hover {
	opacity: 1;
}

.list-container {
	padding-bottom: 100rpx;
}

.total-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 88rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-item {
	display: flex;
	align-items: center;
	
	.value {
		color: #333;
		font-weight: bold;
		margin-left: 10rpx;
	}
}

.total-detail {
	width: 100%;
	background-color: #ffffff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
}

.detail-header {
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 30rpx;
	border-bottom: 1rpx solid #eee;
	position: relative;
	
	.title {
		font-size: 32rpx;
		color: #333;
	}
	
	.close-btn {
		position: absolute;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 44rpx;
		height: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #999;
		font-weight: 100;
	}
}

.detail-content {
	padding: 20rpx 30rpx;
	max-height: 60vh;
	overflow-y: auto;
	display: flex;
	flex-wrap: wrap;
}

.detail-item {
	display: flex;
	// justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	width: 340rpx;
	
	&:last-child {
		border-bottom: none;
	}
	
	.label {
		color: #666;
		font-size: 28rpx;
	}
	
	.value {
		color: #333;
		font-size: 28rpx;
	}
}

.list {
	.list-item {
		position: relative;
		view {
			display: flex;
			justify-content: space-between;
			
			text {
				flex: 1;
				text-align: left;
			}
		}
		&::after {
			content: '';
			position: absolute;
			left: 30rpx;
			right: 30rpx;
			bottom: 0;
			height: 1rpx;
			background-color: #D7DEEB;
		}
		&:last-child::after {
			display: none;
		}
	}
}
</style>
